package net.tngou.jtdb.sql;


import java.io.IOException;
import java.io.StringReader;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.tngou.db.util.ResultSet;
import net.tngou.jtdb.netty.TngouClient;

/**
 * SQL语句操作
 * @author tngou@tngou.net
 *
 */
public class Statement {
	private static Logger log = LoggerFactory.getLogger(Statement.class);
	TngouClient tngouClient = null;
	
	public Statement(TngouClient tngouClient) {
		this.tngouClient=tngouClient;
	}
	
	/**
	 * 执行SQL语句
	 * @param sql
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public ResultSet executeQuery(String sql) throws IOException, InterruptedException
	{
		
		if(tngouClient==null) return new ResultSet(ResultSet.T_ERROR_CONNECT);//返回404
		if(!checkSQL(sql))return new ResultSet(ResultSet.T_ERROR_SQL,"校验SQL语句是不合法");//返回400
		ResultSet resultSet= tngouClient.exe(sql);
		return resultSet;
	}
	
	
	/**
	 * 执行SQL语句
	 * @param sql
	 * @param params
	 * @return
	 */
	public ResultSet execute(String sql,String ... params)  
	{
		
		if(tngouClient==null) return new ResultSet(ResultSet.T_ERROR_CONNECT);//返回404	
		if(!checkSQL(sql))return new ResultSet(ResultSet.T_ERROR_SQL,"校验SQL语句是不合法");//返回400
		if(params!=null)
		{
			String[] cs = StringUtils.split(sql, "?");
			if(cs.length-1!=params.length)
			{
				log.error("SQL："+sql+"与参数个数【"+params.length+"】不能一一对应！");
				return new ResultSet(ResultSet.T_ERROR_SQL,"校验SQL语句是不合法");//返回400
			}
			String key="tndb"+new Date().hashCode();
			sql=StringUtils.replace(sql, "?",key);
			for (String param : params) {
				param=StringUtils.replace(param, "'", "\"");
				sql=StringUtils.replace(sql, key,"'"+param+"'", 1);
			}
			
		}
		if(!checkSQL(sql))return new ResultSet(ResultSet.T_ERROR_SQL,"校验SQL语句是不合法");//返回400

		return tngouClient.exe(sql);
	  
		
	}
	
	/**
	 * 检查是否是SQL语句
	 * @param sql
	 * @return
	 */
	public boolean checkSQL(String sql) {
		try {
			//校验SQL语句是否合法,防止SQL注入
			CCJSqlParserManager manager = new CCJSqlParserManager();
			manager.parse(new StringReader(sql));	
		} catch (JSQLParserException e) {
			log.error("SQL:"+sql+" 非法语句");
			return false;
		}
		return true;
	}
	
	
	
	
}
